<template>
  <div class="scroll" ref="root" :style="{'max-height':maxHeight}">
    <slot></slot>
  </div>
</template>

<script>
import {defineComponent} from 'vue';
import _ from 'lodash';
import {ClickScrollPlugin, OverlayScrollbars, ScrollbarsHidingPlugin, SizeObserverPlugin,} from 'overlayscrollbars';
import 'overlayscrollbars/overlayscrollbars.css';

OverlayScrollbars.plugin([
  SizeObserverPlugin,
  ClickScrollPlugin,
  ScrollbarsHidingPlugin,
]);

export default defineComponent({
  name: 'ArkScroll',
  props: {
    options: {
      type: Object,
    },
    height: {
      type: [String, Number],
      default: '100%'
    }
  },
  data() {
    return {
      scrollInstance: {},
      optionsVariable: {
        scrollbars: {
          // 滚动后自动隐藏滚动条
          autoHide: 'scroll',
        }
      },
    };
  },
  computed: {
    maxHeight() {
      const height = this.height;
      if (!Number.isNaN(Number(height))) {
        return height + 'px';
      }

      return height;
    }
  },
  mounted() {
    this.init();
  },
  beforeUnmount() {
    this.scrollInstance?.destroy();
  },
  methods: {
    init() {
      // 根据传入options初始化optionsVariable
      const options = _.cloneDeep(this.options);
      const optionsVariable = _.cloneDeep(this.optionsVariable);
      this.optionsVariable = _.defaultsDeep(options, optionsVariable);

      // 初始化Scroll
      const el = this.$refs.root;
      this.scrollInstance = OverlayScrollbars(el, this.optionsVariable);
    }
  }
});
</script>

<style scoped>
[data-overlayscrollbars-padding], [data-overlayscrollbars-viewport] {
  z-index: initial;
}
</style>